import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import { Menu, Dropdown, Confirm, Dialog, Form, Input, Button,Message } from '@knownsec/react-component';
import cookie from 'react-cookies';
import logo from '/static/ui_logo.svg';
import person from '@/assets/images/person.png';
import s from './style.module.less';
import { getMailList, putTokenTime,logout as logoutApi } from '~/API/index';
import i from '../../index.module.css';
import cn from 'classnames';
import recursionForm from '@/common/recursionForm';
import { Link } from 'react-router-dom'
import { productInfo } from '~/API/index';
export default function () {
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };
  const [product, setProduct] = useState({
    customer: ''
  })
  const [showArrow, setArrow] = useState(false);
  const [unReadTotal, setUnRead] = useState(0);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const name = cookie.load('username');
  const history = useHistory();
  const logout = () => {
  const refresh = cookie.load('refresh');
    Confirm({
      className: [s.normal],
      pro: true,
      title: '提示',
      message: <div className="confirmbox">确认要退出吗？</div>,
      onconfirm: async () => {
        await logoutApi({refresh})
        cookie.save('refresh', '');
        cookie.save('token', '');
        cookie.save('username', '');
        localStorage.group = ''
        localStorage.info = ''
        localStorage.redirected = ''
        history.push('/login');
      },
      oncancel: () => {},
    });
  };
  const pushMsg = () => {
    history.push('/message');
  };
  const menu = (
    <Menu className={s.w105}>
      <Menu.Item>
      {/* <Link to='/user_edit'>账号设置</Link> */}
      </Menu.Item>
      <Menu.Item>
        <a rel="noopener noreferrer" href="javascript:;" onClick={logout}>
          安全退出
        </a>
      </Menu.Item>
    </Menu>
  );
  const onValues2 = (data) => {
    let values = recursionForm(data);
    const rule = /^\+?[1-9][0-9]*$/;
    if (values.hasOwnProperty('access_token_limit') && !rule.test(values.access_token_limit)) {
      form.current.setFieldsValue({ access_token_limit: '' });
    } else {
      form.current.setFieldsValue(values);
    }
  };
  const submitInfo = () => {
    form.current.validateFields().then(async (data) => {
      const res = await putTokenTime(data);
      setVisible(false);
      form.current.resetFields();
      if (res.status === 'success') {
        Message.show({
          pro: true,
          type: 'success',
          message: '操作成功',
          showClose: false,
        });
      }else{
        Message.show({
          pro: true,
          type: 'error',
          message: `操作失败`,
          showClose: false,
        });
      }
    });
  };
  const getData = () => {
    getMailList({ status: 0 }).then((res) => {
      if (res?.status === 'success') {
        const t = res?.data?.total || 0;
        setUnRead(t);
      }
    });
  };
  React.useEffect(() => {
    productInfo('GET')
      .then((res) => {
        setProduct(res.data);
      })
      .catch((e) => {
        console.log(e)
      });
    getData();
    const seT = setInterval(() => {
        if (name !== cookie.load('username')) {
            window.location.reload() //  更新时判断用户是否变更，如果变更刷新页面重新加载菜单栏
            return false
        }
      getData();
    }, 60 * 1000);
    return () => {
      clearInterval(seT);
    };
  }, []);
  return (
    <div className={s.headerBox}>
      <div className={s.Headerleft}>
        <h2 style={{color: 'white'}}>创宇 WebSOC 网络资产安全检测系统</h2>
      </div>
      {localStorage.group !== '审计员' && (
        <div className={s.Headermenu}>
          <div className={s.msg} onClick={pushMsg}>
            {unReadTotal ? (
              <span className={s.msgIcon}>{unReadTotal > 99 ? '99+' : unReadTotal}</span>
            ) : null}
            <span>消息</span>
          </div>
        </div>
      )}
      <div className={s.Headerright}>
        <Dropdown
          arrow={true}
          overlay={menu}
          placement="bottomRight"
          onVisibleChange={(e) => setArrow(e)}
        >
          <span className={s.dropdowns} onClick={(e) => e.preventDefault()}>
            <img src={person} alt="" />
            {name}
            <span
              className={s.rightIcon}
              style={{ transform: showArrow ? 'rotate(45deg)' : 'rotate(-135deg)' }}
            ></span>
          </span>
        </Dropdown>
      </div>
      <Dialog
        title="账号设置"
        visible={visible}
        confirmText=""
        cancelText=""
        className={s.w540}
        onhide={() => {
          setVisible(false);
          form.current.resetFields();
        }}
      >
        <div className={i.p24}>
          <Form
            ref={form}
            {...layout}
            onValuesChange={(newItem, allValues) => {
              onValues2(newItem, allValues);
            }}
          >
            <Form.Item name="access_token_limit" label="超时设置">
              <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入时间（分钟）'} autoComplete={'off'}/>
            </Form.Item>
          </Form>
        </div>
        <div className={cn(i.tac, s.dioBtn)}>
          <Button className={i.vam} onClick={() => setVisible(false)}>
            取消
          </Button>
          <Button type="primary" className={cn(i.ml24, i.vam)} onClick={() => submitInfo()}>
            确定
          </Button>
        </div>
      </Dialog>
    </div>
  );
}
